package com.site.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class BarCodeUtils {
    /*生成条形码*/
    public void generateCode1(File file, String code, int width, int height){
        // 定义位图矩阵BitMatrix
        BitMatrix matrix = null;
        try {
            // 使用code_128格式进行编码生成100*25的条形码
            MultiFormatWriter writer = new MultiFormatWriter();
            matrix = writer.encode(code, BarcodeFormat.CODE_128, width, height, null);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        // 将位图矩阵BitMatrix保存为图片
        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png", outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*读取条形码*/
    public static void readCode(File readImage) {
        try {
            BufferedImage image = ImageIO.read(readImage);
            if (image == null) {
                return;
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "gbk");
            hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

            Result result = new MultiFormatReader().decode(bitmap, hints);
            System.out.println(result.getText());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*生成二维码*/
    /** 定义二维码的宽度 */
    private final static int WIDTH = 300;
    /** 定义二维码的高度 */
    private final static int HEIGHT = 300;
    /** 定义二维码的格式 */
    private final static String FORMAT = "png";
    /**
     * @param file
     * @param content
     * @return void
     * */
    public static void generateQRCode(File file, String content) {
        // 定义二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 设置编码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置容错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置边距，默认为5
        hints.put(EncodeHintType.MARGIN, 2);

        try {
            BitMatrix bitMatrix = new MultiFormatWriter()
                    .encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            Path path = file.toPath();
            // 保存到项目跟目录中
            MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param file    读取二维码的文件名
     * @return void
     * */
    public static void readQRCode(File file) {
        MultiFormatReader reader = new MultiFormatReader();
        try {
            BufferedImage image = ImageIO.read(file);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = reader.decode(binaryBitmap, hints);
            System.out.println("解析结果: " + new String(result.toString().getBytes("GBK"), "GBK"));
            System.out.println("二维码格式: " + result.getBarcodeFormat());
            System.out.println("二维码文本内容: " + new String(result.getText().getBytes("GBK"), "GBK"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
